package com.novellotus.iov.carvice.alipay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.novellotus.iov.carvice.activity.ConfirmPayActivity;
import com.novellotus.iov.carvice.activity.PaySuccessActivity;
import com.novellotus.iov.carvice.utils.MyUtils;

import java.util.Map;

/**
 * Created by Rich on 2018/3/20.
 */

public class AlipayModel {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016091200490616";
    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCFk30zzT7oh0I+pnGHWwkzMoxkGz61uI1lF/ZPEEt8aZd6WMIQ5+49+hSQa7z7S5pVdEIaG6GGbkjtY6T7mmuQlhiBaWtS1cw0hxM5PhY/KMNkrq1ywj5O/IsGTBgy9Pk9umJomdNCVGQ1OKAjlO5ONldwI4vH2TR3JSVEjc7yuvwwTs1dJXE7GnluXHI0tWrWP+fUMD5TT4mkzH3fw/v+jhFOG9hQpmqNX/ZYYGCLRC/kuFSzGHWkqxsTzVR3cASe4NYngB6SyAddvjX57ecCTqJQmtMAHNu8zKXljMX0bPYTEyIc5ui9Cp5fd4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GAAkNxDFy74dYeB1D/kDL1iI5/gcmYay97qM1VwS3cKWDcoadsjoXc56loe8pIozL4Ert6kFZggxAraC6buBlIt1yQ23luEQLnKO6EI4Hfd0QrB2mDfsMXrga014qF7mlNT6HLZtacfooQ7Hj9h+KuPYeWHaZX7FWAwcREmHlxTlY=";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private Activity activity;

    /**
     * 支付宝支付
     */
    public void aliPay(final Activity activity, final String orderInfo) {
        this.activity = activity;
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
//        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
//        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     {"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2016091200490616","auth_app_id":"2016091200490616","charset":"UTF-8","timestamp":"2018-03-21 16:24:19","total_amount":"0.01","trade_no":"2018032121001004360200235396","seller_id":"2088102175229128","out_trade_no":"180321162345001854"},"sign":"EeK/l+b02MLg32pV6FmFAg4KY3CMIffaJ0TMgYA7GLM4oUBeLaY1u+yFO3b7zfB1bo7yP+AbZonvA/kTKYVLrSqK4MAWAMS28xywIIP8IeITXl/aVLLQEpddIX3xz65g7G24sGqsqouXVvkM9+QIDwTLrnxVnOrDzNHawmIUJUvgc0B9M74KasB5TeNz2QuYkqvrFDHkD+fgfH3IEuGVk5/In/DJGJtxnAoakD9ppDXipcySW1x27ZbjCluuDB3huIDNAwUZiyJfXqXvzS9W107b/LKOYWjCzzQnMqD4/jBa9tUJozCIsRABUg0GDCk8p1A2FncxGi71fcqhmNHT5A==","sign_type":"RSA2"}
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    MyUtils.logInformation("支付宝返回信息：" + resultInfo);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
                        MyUtils.addActivity(activity);
                        Intent intent = new Intent(activity, PaySuccessActivity.class);
                        activity.startActivity(intent);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(activity, "支付失败" + resultInfo, Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(activity,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(activity,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


}
